import React from 'react';
import { connect } from 'react-redux';
import SearchArea from 'components/search-area';
import { messages } from 'share/common';
import ResizeTable from 'components/resize-table';
import SlideFrame from 'components/slide-frame';
import ExportModal from 'components/template/export-modal/export-modal';
import Chooser from 'components/chooser';
import { Form, Popover, Select, Button } from 'antd';
import regionalMarketService from './regional-market.service'
import './regionalMarket.css'

const FormItem = Form.Item;
const { Option } = Select;

class RegionalMarket extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            searchForm: [{
                type: 'input',
                id: 'region',
                label: messages('mcd.basicData.regionalMarket.region'/* 所属区域 */),
                showSearch: true
            }, {
                type: 'input',
                id: 'market',
                label: messages('mcd.basicData.regionalMarket.market'/* 所属市场 */),
                showSearch: true
            }, {
                type: 'input',
                id: 'company',
                label: messages('mcd.basicData.regionalMarket.company'/* 公司名称 */),
                showSearch: true
            }, {
                type: 'input',
                id: 'code',
                label: messages('mcd.basicData.regionalMarket.code'/* 公司编号 */),
                showSearch: true
            }],
            columns: [{
                width: '10%',
                title: messages('common.sequence' /* 序号 */),
                key: 'order',
                dataIndex: 'order',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.region' /* 所属区域 */),
                key: 'area',
                dataIndex: 'area',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.market' /* 所属市场 */),
                key: 'market',
                dataIndex: 'market',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.company' /* 公司名称 */),
                key: 'name',
                dataIndex: 'name',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.code' /* 公司编号 */),
                key: 'code',
                dataIndex: 'code',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.ffl' /* Filed finance lead */),
                key: 'ffl',
                dataIndex: 'ffl',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.hoc' /* Head of Corporate Controlling/Head of Field Finance */),
                key: 'hoc',
                dataIndex: 'hoc',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.vpcc' /* Vp-Corporate Controller */),
                key: 'vpcc',
                dataIndex: 'vpcc',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.vp' /* 市场人事负责人\人力资源部VP */),
                key: 'vp',
                dataIndex: 'vp',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.ma' /* 公司事务经理 */),
                key: 'ma',
                dataIndex: 'ma',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('components.key1372' /* 公司活动费审批人 */),
                key: 'com',
                dataIndex: 'com',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '20%',
                title: messages('mcd.basicData.regionalMarket.tax' /* tax manager */),
                key: 'tax',
                dataIndex: 'tax',
                render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span >
            }, {
                width: '10%',
                title: messages('common.operation' /* 操作 */),
                key: 'action',
                dataIndex: 'action',
                render: (text, record) => <div>
                  <a className="tableText editText" href="javascript:void(0);" onClick={() => this.handleOnEdit(record)}>修改</a>
                </div>
            }],
            pagination: {
                current: 1,
                page: 0,
                total: 0,
                size: 10,
                showSizeChanger: true,
                showQuickJumper: true
            },
            searchCondition: { all: false },
            data: [],
            loading: true,
            slideFrameKey: 'slideFrameKey0',
            visible: false,
            selectedRecord: {}
        }
    }

    componentDidMount () {
        this.getListData()
    }

    /**
   * 根据关键字和页码去查询区域市场列表
   * @param {Object} values
   */
    getListData = async (values = {}) => {
        const { pagination } = this.state
        let url = `?size=${pagination.size}&page=${pagination.page}`
        for (const key in values) {
            if (values[key]) {
              url += `&${key}=${values[key]}`
            } else if (!values[key]) {
              delete values[key]
            }
        }
        const res = await regionalMarketService.getListData(url)
        const dataTemp = res.data.map((record, index) => {
            record.order = index + 1;
            return record;
        });
        pagination.total = Number(res.headers['x-total-count']) || 0
        this.setState({
            data: dataTemp,
            pagination,
            loading: false
        })
    }

    /**
   * 重置搜索框
   */
    clearHandle = () => {
        const { pagination } = this.state
        this.setState({
            loading: true,
            pagination: {
                current: 1,
                page: 0,
                size: pagination.size,
                total: pagination.total
            },
            searchCondition: { all: false }
        }, () => {
            this.getListData()
        })
    }

    /**
   * 搜索
   * values: 搜索表单的所有组件的值
   */
    handleSearch = (values) => {
        const { pagination } = this.state
        const downloadCondition = {}
        downloadCondition.all = false
        downloadCondition.region = values.region
        downloadCondition.market = values.market
        downloadCondition.company = values.company
        downloadCondition.code = values.code
        this.setState({
            loading: true,
            pagination: {
                current: 1,
                page: 0,
                size: pagination.size,
                total: pagination.total
            },
            searchCondition: downloadCondition
        }, () => {
            this.getListData(values)
        })
    }

    /**
   * 修改每页最大显示数据数量、页码跳转触发
   * @param {Object} pagination
   */
    onChangePage = (pagination) => {
        const { searchCondition } = this.state
        this.setState({
            pagination: {
                current: pagination.current,
                page: pagination.current - 1,
                size: pagination.pageSize,
                total: pagination.total
            },
            loading: true
        }, () => {
            this.getListData(searchCondition)
        })
    }

    /**
   * 点击显示编辑抽屉
   * 1、显示右侧编辑抽屉
   * 2、根据接口获取这一条数据的详细信息并填充到编辑抽屉内部的表单
   * @param {Object} record
   */
    handleOnEdit = (record) => {
        const { slideFrameKey } = this.state;
        this.props.form.setFieldsValue({
            ffl: record.ffl ? [{fullName: record.ffl, employeeID: record.fflEid}] : [],
            hoc: record.hoc ? [{fullName: record.hoc, employeeID: record.hocEid}] : [],
            vpcc: record.vpcc ? [{fullName: record.vpcc, employeeID: record.vpccEid}] : [],
            tax: record.tax ? [{fullName: record.tax, employeeID: record.taxEid}] : [],
            com: record.com ? [{fullName: record.com, employeeID: record.comEid}] : []
        })
        this.setState({
            selectedRecord: record,
            visible: true,
            slideFrameKey: slideFrameKey + 1
        })
    }

    /**
   * 关闭抽屉
   */
    handleOnHideSlide = () => {
        this.setState({
            visible: false
        })
    }

    /**
   * 抽屉编辑基本信息保存
   */
    handleOnCreateAndEdit = (e) => {
        e.preventDefault();
        const { selectedRecord } = this.state
        this.props.form.validateFieldsAndScroll((err, values) => { 
            if (!err) {
                const result = {}
                result.code = selectedRecord.code
                result.ffl = values.ffl.length > 0 ? values.ffl[0].employeeID : ''
                result.hoc = values.hoc.length > 0 ? values.hoc[0].employeeID : ''
                result.tax = values.tax.length > 0 ? values.tax[0].employeeID : ''
                result.com = values.com.length > 0 ? values.com[0].employeeID : ''
                result.vpcc = values.vpcc.length > 0 ? values.vpcc[0].employeeID : ''
                this.handleOnEditSave(result)
            }
        })
    }

    /**
   * 调用抽屉编辑基本信息保存接口
   */
  handleOnEditSave = async (values) => {
    const { searchCondition } = this.state;
    const res = await regionalMarketService.updateData(values);
    this.setState({
      visible: false,
      loading: true
    }, () => {
      this.getListData(searchCondition);
    })
  }

    /**
   * 渲染编辑抽屉
   */
    renderEditAndAdd = () => {
        const { getFieldDecorator } = this.props.form
        const { selectedRecord } = this.state
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 12, offset: 1 },
        }
        return (
            <div>
                <Form onSubmit={this.handleOnCreateAndEdit}>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.ffl' /* Field Finance Lead */)}
                    >
                        {getFieldDecorator('ffl', {
                            initialValue: [],
                            rules: [{ required: false }]
                        })(
                            <Chooser
                                single
                                placeholder={messages('common.please.select')}
                                labelKey="fullName"
                                valueKey="employeeID"
                                type="user"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.hoc' /* Head of Corporate Controlling/Head of Field Finance */)}
                    >
                        {getFieldDecorator('hoc', {
                            initialValue: []
                        })(
                            <Chooser
                                single
                                placeholder={messages('common.please.select')}
                                labelKey="fullName"
                                valueKey="employeeID"
                                type="user"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.vpcc' /* Vp-Corporate Controller */ )}
                    >
                        {getFieldDecorator('vpcc', {
                            initialValue: []
                        })(
                            <Chooser
                                single
                                placeholder={messages('common.please.select')}
                                labelKey="fullName"
                                valueKey="employeeID"
                                type="user"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.vp' /* 市场人事负责人\人力资源部VP */)}
                    >
                        {selectedRecord.vp}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.ma' /* 公司事务经理 */)}
                    >
                        {selectedRecord.ma}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('mcd.basicData.regionalMarket.tax' /* tax manager */)}
                    >
                        {getFieldDecorator('tax', {
                            initialValue: []
                        })(
                            <Chooser
                                single
                                placeholder={messages('common.please.select')}
                                labelKey="fullName"
                                valueKey="employeeID"
                                type="user"
                            />
                        )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label={messages('components.key1372' /* 公司活动费审批人 */)}
                    >
                        {getFieldDecorator('com', {
                            initialValue: []
                        })(
                            <Chooser
                                single
                                placeholder={messages('common.please.select')}
                                labelKey="fullName"
                                valueKey="employeeID"
                                type="user"
                            />
                        )}
                    </FormItem>
                    <div className="slide-footer">
                        <Button type="primary" htmlType="submit">{messages('common.save')}</Button>
                        <Button onClick={this.handleOnHideSlide}>{messages('common.cancel')}</Button>
                    </div>
                </Form>
            </div>
        )
    }

    render() {
        const { pagination, searchCondition, data, loading, columns, slideFrameKey, visible } = this.state
        return (
          <div>
              <SearchArea
                searchForm={this.state.searchForm}
                clearHandle={this.clearHandle}
                submitHandle={this.handleSearch}
                />
            <div className="totalNum">
                {messages('common.total', { total: pagination.total || 0 })/*共搜索到 {total} 条数据*/}
            </div>
            <div className="btnsContainer">
                <ExportModal
                    type="btn"
                    exportTitle={messages('setting.key302')}
                    exportType="MARKET_USER"
                    exportCommand={'MARKET_USER'}
                    exportCondition={{ carDownloadCommand: searchCondition }}
                />
            </div>
            <ResizeTable
                rowKey={'id'}
                dataSource={data}
                loading={loading}
                pagination={pagination}
                onChange={this.onChangePage}
                columns={columns}
                size="middle"
                bordered
                />
            <SlideFrame
                slideFrameKey={slideFrameKey}
                title={messages('mcd.basicData.regionalMarket.edit')}
                width={'730px'}
                show={visible}
                content={this.renderEditAndAdd}
                onClose={this.handleOnHideSlide}
                />
          </div>  
        )
    }
}

RegionalMarket.contextTypes = {
    router: React.PropTypes.object
}
  
function mapStateToProps(state) {
    return {
        organization: state.budget.organization,
        company: state.login.company,
        language: state.main.language,
        tenantMode: state.main.tenantMode
    }
}
  
  export default connect(mapStateToProps)(Form.create()(RegionalMarket));